#coding:utf-8

from mako.template import Template as Mako_Template
from mako.runtime import Context as Mako_Context

import data
import sys

TEMPLATE_FILE_PATH = 'htmlreport.html'

def make_report(datapath, reportpath, **kw):
    session = kw.get('session', data.Session(bind=data.get_engine(datapath)))
    tc_list = session.query(data.TestCase).all()
    tlist, tp = [], {}
    for tc in tc_list:
        mod = tc.path.rsplit('.', 1)[0]
        if not tp.has_key(mod):
            d = {'cases': [], 'fail':0, 'pass':0, 'name': mod}
            tlist.append(d)
            tp[mod] = d
        mk = tp[mod]
        mk['cases'].append(tc)
        for result in tc.results:
            if result.result is False:
                mk['fail'] += 1
                break
        else:
            mk['pass'] += 1
    description = {
                   'time start': kw.get('time_start', 'Empty'),
                   'time stop': kw.get('time_stop', 'Empty'),
                   'title': kw.get('title', 'Test Report'),
                   'status': kw.get('status', 'Empty'),
                   }
    t = Mako_Template(filename=TEMPLATE_FILE_PATH)
    f = file(reportpath, 'w')
    try:
        c = Mako_Context(f, results=tlist, description=description)
        t.render_context(c)
    finally:
        f.close()
        
if __name__ == '__main__':
    try:
        datapath = sys.path[1]
        reportpath = sys.path[2]
        make_report(datapath, reportpath)
    except:
        print "Usage"